﻿using log4net.Config;
using SelfMadeMillionaire.BLL;
using SelfMadeMillionaire.BLL.Services;
using SelfMadeMillionaire.Core;
using SelfMadeMillionaire.Core.Enums;
using SelfMadeMillionaire.Core.Repositories;
using SelfMadeMillionaire.DAL;
using SelfMadeMillionaire.DAL.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
using System.Configuration;

namespace SelfMadeMillioniare.MailingListSender
{
	class Program
	{
		static void Main(string[] args)
		{
            //NotificationHelper.Instance.SendAppleNotification("2f7c5e2c7b4ef6d1cbce774ff30eab6f5e983dfb995d50005ce2f898d30d31f0", "You have a new trade alert");
            //return;

            if (args.Length == 0 || (args[0].ToLower() != "emails" && args[0].ToLower() != "subscriptions"))
            {
                Console.WriteLine("usage: SelfMadeMillioniare.MailingListSender.exe <emails|subscriptions>");
                Console.WriteLine("press any key to continue...");
                Console.ReadKey();
            }
            else
            {
                Process[] processess = Process.GetProcessesByName("SelfMadeMillioniare.MailingListSender");
                if (processess.Length > 1)
                    return;

                try
                {
                    XmlConfigurator.Configure();
                    using (var ctx = new DataContext())
                    {
                        if (args[0].ToLower() == "subscriptions")
                        {
                            new MailingListService(
                                new EmailMessageRepository(ctx)
                                , new EmailService(new LogRepository(ctx))
                                , new PublicationRepository(ctx)
                                , new NewsletterRepository(ctx)
                                , new EmailMessageSendRepository(ctx)).SendMailingList();
                        }
                        else
                        {
                            new EmailSendService(new EmailSendRepository(ctx), new EmailService(new LogRepository(ctx)), new SubscriberRepository(ctx)).SendEmailTemplates();
                        }
                    }
                }
                catch (Exception ex)
                {
                    new LoggingUtility().WriteErrorToLog(ex);

                    try
                    {
                        var es = new EmailService(new LogRepository(null));
                        es.SendEmails(ConfigurationManager.AppSettings["AdminEmail"], "SMM sending error", ex.Message);
                    }
                    catch { }
                }
            }
		}
	}
}
